<template>
  <van-nav-bar
    title="列表"
    left-text="返回"
    left-arrow
    @click-left="
      () => {
        $router.push('/');
      }
    "
    fixed
    placeholder
  />

  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <!-- 商品卡片 -->
      <van-card
        v-for="item in list"
        :price="item.goods_price"
        :title="item.goods_name"
      >
        <!-- 手写插槽 -->
        <template #thumb>
          <img
            :src="
              item.goods_big_logo
                ? item.goods_big_logo
                : 'https://tse1-mm.cn.bing.net/th/id/OIP-C.2IRCeI7lpFjVDkDwqMseBQHaEo?rs=1&pid=ImgDetMain'
            "
            alt=""
            style="width: 88px; height: 88px"
          />
        </template>
      </van-card>
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
import { ref } from "vue";
import { goodsApi } from "@/api/api";
import { useRoute } from "vue-router";
let route = new useRoute();
console.log(route.params.cat_id);

//列表数据
const list = ref([]);
//当前页
let page = ref(1);
//每页个数
let pagesize = ref(5);
//总条数
let total = ref(0);
let loading = ref(false);
let finished = ref(false);
let refreshing = ref(false);
const goodsData = () => {
  goodsApi(route.params.cat_id).then((res) => {
    console.log("列表数据", res);
    //   list.value = res.data.message.goods;
    //自定义切割
    let startindex = (page.value - 1) * pagesize.value;
    let endindex = startindex + pagesize.value;
    list.value = res.data.message.goods.slice(startindex, endindex);
    if (list.value >= total.value) {
      finished.value = true;
    }
  });
};
goodsData();

//下拉刷新
const onRefresh=()=>{
    page.value=2
    list.value=[]
    finished.value=false
    refreshing.value=false
    goodsData()
}

//上拉加载   异步 async await
const onLoad=async()=>{
    if(finished.value)return
    const res=await goodsApi()
    
    page.value++
    let startindex = (page.value - 1) * pagesize.value;
    let endindex = startindex + pagesize.value;
    let newData=res.data.message.goods.slice(startindex,endindex)
    //合并
    list.value=[...list.value,...newData]
    if(list.value>=total.value){
        loading.value=false
    }
}
</script>

<style lang="scss" scoped></style>
